﻿namespace Dissemination.MVC.Repositories
{
    using System.Linq;
    using System.Collections.Generic;
    using Dissemination.MVC.Models;

    public class SurveyRepository : BaseRepository<Survey>
    {
        public SurveyRepository()
        {
            EntityName = "Surveys";
        }

        public override List<Survey> List()
        {
            return dataContext.Surveys.ToList();
        }

        public Program GetProgramByID(int programID)
        {
            return dataContext.Programs.Include("TargetAreas").FirstOrDefault(p => p.ProgramID == programID);
        }

        public Survey GetLastSurveyByProgram(int programID)
        {
            var surveys = (from s in dataContext.Surveys
                               where (s.Program.ProgramID == programID)
                               orderby s.SurveyOrdinal descending
                               select s);

            return surveys.FirstOrDefault();
        }

        public override Survey Get(int id)
        {
            return dataContext.Surveys.Include("Program").FirstOrDefault(s => s.SurveyID == id);
        }

        public override void Add(Survey obj)
        {


            Survey lastSurvey = GetLastSurveyByProgram(obj.Program.ProgramID);
            int ordinal = lastSurvey == null ? 1 : lastSurvey.SurveyOrdinal + 1;
            obj.SurveyOrdinal = ordinal;
            base.Add(obj);
        }
    }
}
